package com.baize.filedowndemo

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.ProgressBar
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.liulishuo.okdownload.DownloadTask
import com.liulishuo.okdownload.OkDownload
import com.liulishuo.okdownload.StatusUtil
import com.liulishuo.okdownload.core.cause.EndCause
import com.liulishuo.okdownload.core.cause.ResumeFailedCause
import com.liulishuo.okdownload.core.listener.DownloadListener3
import com.liulishuo.okdownload.core.listener.assist.Listener1Assist
import java.io.File
import java.lang.Exception
import kotlin.math.log


class MulitDownActivity : AppCompatActivity() {

  val DOWNLOAD_URL =
    "https://oss-doufan-story.oss-cn-hangzhou.aliyuncs.com/upload/cdn/app-debug.apk"

  lateinit var progressbar1: ProgressBar
  lateinit var progressbar2: ProgressBar

  //listener3 https://github.com/lingochamp/okdownload/wiki/Simple-Use-Guideline

  val progressListener: OkDownloadListener by lazy {
    object : OkDownloadListener {
      override fun onProgress(task: DownloadTask, progress: Int) { //找到View 更新进度
        if (task.filename == "test1.apk") {
          progressbar1.progress = progress
        }
        if (task.filename == "test2.apk") {
          progressbar2.progress = progress
        }
      }
    }
  }

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_mulit_down)
    findViewById<Button>(R.id.down_task_1).setOnClickListener {
      OkDownloadManager.startDownloadTask(DOWNLOAD_URL, "test1.apk")
    }
    findViewById<Button>(R.id.down_task_2).setOnClickListener {
      OkDownloadManager.startDownloadTask(DOWNLOAD_URL, "test2.apk")
    }
    progressbar1 = findViewById(R.id.progressbar_1)
    progressbar2 = findViewById(R.id.progressbar_2)

    findViewById<Button>(R.id.status_task_1).setOnClickListener {
      val task = OkDownloadManager.createDownloadTask(DOWNLOAD_URL to "test1.apk")
      val status = StatusUtil.getStatus(task)
      Log.i("baize_","任务一状态：${status.toString()}")
    }

    //获取正在下载中的任务 关联相关的任务进度
    val task = createDownloadTask(DOWNLOAD_URL to "test1.apk")
    val exitTask = OkDownload.with().downloadDispatcher().findSameTask(task)
    Log.i("baize_", "onCreate: ${exitTask != null} ${task.toString()} == ${exitTask.toString()}")

    OkDownloadManager.addObserve(progressListener)
    lifecycle.addObserver(object : LifecycleObserver {
      fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        if (event == Lifecycle.Event.ON_DESTROY) {
          Log.i("baize_", "onStateChanged: ON_DESTROY 移除监听！")
          OkDownloadManager.removeObserve(progressListener)
        }
      }
    })
  }


  private fun createDownloadTask(itemInfo: Pair<String, String>): DownloadTask {
    return DownloadTask.Builder(itemInfo.first, getCacheDir()) //设置下载地址和下载目录，这两个是必须的参数
      .setFilename(itemInfo.second) //设置下载文件名，没提供的话先看 response header ，再看 url path(即启用下面那项配置)
      //      .setFilenameFromResponse(false) //是否使用 response header or url path 作为文件名，此时会忽略指定的文件名，默认false
      .setPassIfAlreadyCompleted(true) //如果文件已经下载完成，再次下载时，是否忽略下载，默认为true(忽略)，设为false会从头下载
      //      .setConnectionCount(1) //需要用几个线程来下载文件，默认根据文件大小确定；如果文件已经 split block，则设置后无效
      //      .setPreAllocateLength(false) //在获取资源长度后，设置是否需要为文件预分配长度，默认false
      .setMinIntervalMillisCallbackProcess(100) //通知调用者的频率，避免anr，默认3000
      .setWifiRequired(false) //是否只允许wifi下载，默认为false
      .setAutoCallbackToUIThread(true) //是否在主线程通知调用者，默认为true
      //.setHeaderMapFields(new HashMap<String, List<String>>())//设置请求头
      //.addHeader(String key, String value)//追加请求头
      .setPriority(0) //设置优先级，默认值是0，值越大下载优先级越高
      .setReadBufferSize(4096) //设置读取缓存区大小，默认4096
      .setFlushBufferSize(16384) //设置写入缓存区大小，默认16384
      .setSyncBufferSize(65536) //写入到文件的缓冲区大小，默认65536
      .setSyncBufferIntervalMillis(2000) //写入文件的最小时间间隔，默认2000
      .build()
  }
}